//
//  XLOAuthViewController.swift
//  SinaWeibo
//
//  Created by 李凯 on 16/9/3.
//  Copyright © 2016年 kevin. All rights reserved.
//

import UIKit
import SVProgressHUD

// OAuth授权所需要一系列信息
let WB_APPKEY = "2348348555"
let WB_SECRET = "ac9334f87bfce513603c6feab7c9c30d"
let WB_REDIRECT_URL = "http://www.itheima.com/"

class XLOAuthViewController: UIViewController, UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    func setupUI() {
        view.backgroundColor = UIColor.white
        navigationItem.title = "新浪微博-登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(fillClick))
        
        //添加到视图
        view.addSubview(webView)
        //布局
        webView.snp_makeConstraints { (make)  -> Void in
            make.edges.equalTo(self.view)
        }
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URL)"
        //webView加载请求
        let url = URL(string: urlString)!
        let request = URLRequest(url: url)
        webView.loadRequest(request)
        
    }
    
    func cancelClick() {
        dismiss(animated: true, completion: nil)
    }
    
    func fillClick() {
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'likai_new@sina.cn';document.getElementById('passwd').value = '61241022lkx';")
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let u = request.url {
            let urlString = u.absoluteString
            //如果前缀不是回调页, 才加载
            if !urlString.hasPrefix(WB_REDIRECT_URL) {
                return true
            }
        }
        //执行到这一行 说明是回调页 是回调页就需要return false
        //获取url中的查询字符串
        if let query = request.url?.query{
            //print(query)
            //从查询字符串中截取code
            let code  = query.substring(from: "code=".endIndex)
            print("\(code)")
            //获取accessToken
            //loadAccessToken(code: code)
            XLUserAccountViewModel.sharedModel.loadAccessToken(code: code, completion: { (isSuccess) in
                if isSuccess {
                    //切换根控制器 到 欢迎页
                    //模态出来的控制器要dismiss
                    self.dismiss(animated: true, completion: {
                        NotificationCenter.default.post(name: NSNotification.Name(XLChangeRootVCNotification), object: self)
                    })
                }else{
                    print("登录出错")
                }
            })
        }
        
        return false
    }
    
    //开始加载的时候
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //加载完毕的时候
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载出错的时候
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    //懒加载
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        // 设置代理
        webView.delegate = self
        return webView
    }()

}
